package cn.ubest.mvvmcore.base

import androidx.lifecycle.MutableLiveData
import cn.ubest.mvvmcore.bean.*

/**
 * Created by maoqi on 2020/9/23.
 */
abstract class BaseListViewModel<M : BaseModel> : BaseViewModel<M>() {
    val mListLiveData by lazy {
        MutableLiveData<ListDataLoader<Any>>()
    }
    var pageSize = 20
    private val startPageNum = 1
    var curPageNum = startPageNum

    fun setData(list: List<Any>?) {
        var state: Int
        if (list == null) {
            state = if (isInitPage()) {
                //如果是刷新
                ListLoadState.INIT_LOAD_END
            } else {
                ListLoadState.LOAD_END
            }
            mListLiveData.postValue(ListDataLoader<Any>(state, arrayListOf()))
        } else {
            state = if (isInitPage()) {
                //如果是刷新
                if (isLoadEnd(list)) {
                    ListLoadState.INIT_LOAD_END
                } else {
                    ListLoadState.INIT_LOAD_COMPLETE
                }
            } else {
                if (isLoadEnd(list)) {
                    ListLoadState.LOAD_END
                } else {
                    ListLoadState.LOAD_COMPLETE
                }
            }
            mListLiveData.postValue(ListDataLoader<Any>(state, ArrayList(list)))
            curPageNum++
        }
    }

    /**
     * 是否已经加载完成
     */
    open fun isLoadEnd(list: List<*>): Boolean {
        return list.size < pageSize
    }

    /**
     * 重置mCurPage
     */
    private fun resetCurPage() {
        curPageNum = startPageNum
    }

    /**
     * 是否是加载第一页
     */
    fun isInitPage(): Boolean {
        return curPageNum == startPageNum
    }

    /**
     * 加载数据
     */
    abstract fun loadData(isInit: Boolean, vararg arg: Any)

    fun loadData(vararg arg: Any) {
        loadData(false, *arg)
    }

    /**
     * 刷新数据
     */
    open fun refreshData(vararg arg: Any) {
        resetCurPage()
        loadData(true, *arg)
    }
}